<?php
declare(strict_types=1);

namespace HiCommon\Service;

use HiCommon\Helper;
use HiCommon\Repository\AreasRepository;
use HiCommon\Repository\OrderMallRepository;
use HiCommon\Repository\StoreOrderRefundRepository;
use HiCommon\Repository\StoreOrderRepository;
use HiCommon\Repository\GiftRepository;
use HiCommon\Repository\CouponGrantDetailRepository;
use HiCommon\Repository\LogRepository;
use HiCommon\Repository\UserInviteRepository;
use HiCommon\Repository\UsersRepository;
use HiCommon\Repository\UsersLevelRepository;
use HiCommon\Repository\EquitiesRepository;
use HiCommon\Repository\CouponsRepository;
use HiCommon\Repository\UsersIntegralRepository;
use HiCommon\Repository\ActivityRepository;
use HiCommon\Repository\SensitivityRepository;

class PublicService
{
    /**
     * 获取省列表
     */
    public function getProvinceList()
    {
        $province = AreasRepository::get_list(['level' => 1]);
        $list = array();
        foreach ($province as $key => $item) {
            $list[$item['id']] = $item['name'];
        }
        return $list;
    }

    /**
     * 获取列表
     */
    public function getCityList(array $data)
    {
        $res = AreasRepository::get_list($data);

        if (empty($res)) {
            return hello_error('失败');
        }

        $html = '<option value="">请选择</option>';
        foreach ($res as $key => $item) {
            $html .= '<option value="' . $item["id"] . '">' . $item["name"] . '</option>';
        }

        return hello_success('成功', $html);
    }

    /**
     * 获取列表
     */
    public function getCityAraeList(array $data)
    {
        $province = AreasRepository::get_list($data);
        $list = array();
        foreach ($province as $key => $item) {
            $list[$item['id']] = $item['name'];
        }

        return $list;
    }

    /**
     * 区域坐标
     * @param array $data
     * @return mixed
     */
    public function areaCoordinate(array $data)
    {
        $arr_where['id'] = $data['id'];
        $arr_option['field'] = ['id', 'Lng', 'Lat'];
        $info = AreasRepository::base_get_one($data, $arr_option);

        $result = [
            'id' => $info['id'],
            'Lng' => number_format($info['Lng'],6),
            'Lat' => number_format($info['Lat'],6)
        ];
        return $result;
    }

    /**
     * 物流追踪
     */
    public function logistics_tracking($order_id, $type)
    {
        try {
            if ($order_id <= 0) {
                return hello_error('订单id不能为空');
            }
            $arr_option['field'] = ['id', 'xpress_id', 'delivery_no'];
            if ($type == 1) { //积分订单
                $arr_option['with'] = ['getExpressInfo'];
                $res = OrderMallRepository::get_one($order_id, $arr_option);
                if ($res->first()) {
                    $result = $res->toarray();
                    $delivery_no = $result['delivery_no'];
                    $delivery_type = $result['get_express_info']['type'];
                }
            } elseif ($type == 2) {//普通商品订单
                $arr_option['with'] = ['getExpress'];
                $res = StoreOrderRepository::get_one($order_id, $arr_option);
                if ($res->first()) {
                    $result = $res->toarray();
                    $delivery_no = $result['delivery_no'];
                    $delivery_type = $result['get_express']['type'];
                }
            } elseif ($type == 3) {
                $refund['with'] = ['getExpress'];
                $res = StoreOrderRefundRepository::get_one($order_id, $refund);

                if ($res->first()) {
                    $result = $res->toarray();
                    $delivery_no = $result['express_no'];
                    $delivery_type = $result['get_express']['type'];
                }
            } else {
                return hello_error('订单类型错误');
            }

            if ($delivery_no && $delivery_type) {
                $info = json_decode(kuaidi_search($delivery_no, $delivery_type), true);
                if (empty($info)) {
                    return hello_error('物流查询费用不足，请联系商家或平台');
                } else if ($info['status'] == '0') {
                    return hello_success('获取成功', $info);
                } else {
                    return hello_error($info['msg']);
                }
            }

            return hello_error('暂无物流信息');
        } catch (\Exception $exception) {
            return ['state' => 1, 'msg' => '失败', 'data' => [], 'error' => $exception->getMessage()];
        }
    }


    /**
     *  新用户注册礼包
     *  hinq 2020 3 11
     *
     **/
    public function send_gift_regiset(int $user_id)
    {
        /**
         *  1:每次新注册的用户都需要调用次函数
         *  2：验证新用户注册礼包是否开启
         *  3：获取新用户注册礼包设置的礼包数据信息（car_gifts和car_gift_extend）
         *  4：将新用户注册礼包发放到新用户账户中（car_coupon_grant_detail）
         *  5：记录发放日志
         **/
        // 获取保存的日志信息
        // dd( LogRepository::get_send_gift_log()->toarray());
        //验证注册礼包是否开启（由于现在控制功能为完善，暂且不验证）
        //验证当前用户是都已经发放过用户注册礼包
//        $where['type'] = 4;   //     1：会员等级升级礼包   2：分享邀请获得 3：会员手动领取优惠券  4：:新用户注册奖励  52：2年老用户回馈礼包   53：3年老用户回馈礼包  55：5年老用户回馈礼包
//        $where['user_id'] = $user_id;
//        $count = CouponGrantDetailRepository::get_count_by_where( $where );
//        /* if( $count > 0 ){  //当前用户已经发放过新用户注册礼包
//             return hello_success('ok');
//         }*/
        //获取当前用户信息  判断当前用户是否为新用户
        $arr_option_user['field'] = ['id', 'is_new_user'];
        $arr_user_info = UsersRepository::get_one($user_id, (array)$arr_option_user);
        if (empty($arr_user_info->first())) {
            return hello_error('礼包发放失败');
        }
        $arr_user_info = $arr_user_info->toarray();
        if ($arr_user_info['is_new_user'] != 1) {  //当前用户不是新用户
            return hello_error('当前用户不是新用户');
        }

        //获取平台设置的用户注册礼包数据
        $where['type'] = 1;
        $arr_option['field'] = ['id', 'type', 'title', 'age', 'number'];
        $arr_option['with'] = ['extend'];
        //获取指定数据的详细信息
        $arr_list = GiftRepository::get_one_by_where((array)$where, (array)$arr_option);
        UsersRepository::edit_one((array)['id' => $user_id, 'is_new_user' => 2]);  //将用户修改为老用户

        if (empty($arr_list->first())) {   // 没有设置新用户注册礼包
            $arr_send_data = [
                'xcq' => 0,
                'mjq' => 0,
                'zkq' => 0,
                'msg' => '暂未配置新用户注册礼包'
            ];
            return hello_success('ok', $arr_send_data );
        }
        $arr_list = $arr_list->toarray();

        $temp['user_id'] = $user_id;
        $temp['msg'] = '新用户注册礼包';
        $temp['integral'] = 0;
        $temp['status'] = 1;
        $temp['type'] = 4;
        $xcq = 0;
        $zkq = 0;
        $mjq = 0;
        $num = 0;
        //给用户发放新用户注册礼包
        foreach ($arr_list['extend'] as $key => $value) {
            for ($i = 1; $i <= $value['number']; $i++) {
                if ($value['type_coupon'] == 1) {
                    $xcq++;
                } else if ($value['type_coupon'] == 2) {
                    $mjq++;
                } else if ($value['type_coupon'] == 3) {
                    $zkq++;
                }
                $num++;
                $temp['coupon_id'] = $value['coupon_id'];
                $temp['pid'] = $value['type_coupon'];
                $temp['over_at'] = time() + $value['validity_at'] * 60 * 60 * 24;
                $temp['ticket_num'] = set_coupons_ticket_num($value['type_coupon']);
                CouponGrantDetailRepository::add_one($temp);
            }
        }
        $str = '已发放洗车券：' . $xcq . '张，满减券：' . $mjq . '张，折扣券：' . $zkq . '张,共计发放' . $num . '张';
        $arrlog = [
            'user_id' => $user_id,
            'send_time' => date('Y-m-d H:i:s'),
            'msg' => $str,
            'type' => 1,
            'type_msg' => '新用户注册礼包'
        ];
        $msg = '';
        if ($xcq > 0) {
            $msg = '洗车券X' . $xcq;
        }
        if ($mjq > 0) {
            $msg .= '，满减券X' . $mjq;
        }
        if ($zkq > 0) {
            $msg .= '，折扣券X' . $zkq;
        }
        $arr_send_data = [
            'xcq' => $xcq,
            'mjq' => $mjq,
            'zkq' => $zkq,
            'msg' => $msg
        ];
        //将发放新用户注册礼包的记录记录日志
        LogRepository::record_send_gift((array)$arrlog);
        return hello_success('ok', $arr_send_data);
    }

    /**
     *  app端邀请请求接口    用户邀请礼包发放  中转站
     *  $username    邀请者唯一标示
     *  $to_user_id  被邀请者id
     *  \HiCommon\Service\PublicService\send_gift_invite_after(  (string) $username  , (int) $to_user_id)
     **/
    public function send_gift_invite_after(string $username, int $to_user_id)
    {
        if (empty($username)) {
            return hello_error('参数错误');
        }
        if (empty($to_user_id)) {
            return hello_error('被邀者不能为空');
        }
        //获取当前邀请者的用户id
        $where['username'] = $username;
        $arr_option['field'] = ['id'];
        $arr_info = UsersRepository::get_one_where($where, $arr_option);
        if (empty($arr_info)) {
            return hello_error('参数错误');
        }
        return self::send_gift_invite((int)$arr_info['id'], (int)$to_user_id);
    }


    /**
     *  用户邀请礼包发放
     *  $user_id       邀请者id
     *  $to_user_id    被邀请者id
     **/
    public function send_gift_invite(int $user_id, int $to_user_id)
    {
        try {
            /**
             *  1：每次邀请新用户注册后调用次函数
             *  2：验证邀请礼包是否开启
             *  3：验证邀请用户和被邀请用户数据的有效性
             *  4：添加邀请信息
             *  5：计算当前次数邀请是否满足邀请礼包的发放
             *  6：发放邀请礼包
             *  7：记录邀请礼包发放日志
             **/
            //验证邀请礼包是否开启（由于现在控制功能为完善，暂且不验证）

            //验证数据的有效性
            //是否重复提交数据

            $where = ['user_id' => $user_id, 'to_user_id' => $to_user_id];
            $count = UserInviteRepository::get_count_by_where((array)$where);
            if ($count > 0) {
                return hello_error('请勿重复提交');
            }
            unset($where);
            //被邀请者是否只被邀请过一次
            $where = ['to_user_id' => $to_user_id];
            $count = UserInviteRepository::get_count_by_where((array)$where);
            if ($count > 0) {
                return hello_error('被邀请者被重复邀请');
            }
            $data['user_id'] = $user_id;
            $data['to_user_id'] = $to_user_id;
            $data['type'] = 0;

            $res = UserInviteRepository::add_one((array)$data);
            \DB::beginTransaction();      //开启事物
            //统计邀请者已邀请且未别计算的人数
            unset($where);
            $where = ['user_id' => $user_id, 'type' => 0];
            $count = UserInviteRepository::get_count_by_where((array)$where);

            //获取平台设置的邀请者礼包
            //获取平台设置的用户注册礼包数据
            unset($where);
            $where['type'] = 3;
            $arr_option['field'] = ['id', 'number'];
            $arr_option['with'] = ['extend'];
            //获取指定数据的详细信息
            $arr_list = GiftRepository::get_one_by_where((array)$where, (array)$arr_option);
            if (empty($arr_list->first())) {
                return hello_error('未设置邀请礼包');
            }
            $arr_list = $arr_list->toarray();
            //邀请人数  >= 平台设置邀请人数
            if ($count < $arr_list['number']) {   //给邀请者发放邀请礼包
                return hello_success('邀请人数不满足邀请礼包的发放');
            }
            $xcq = 0;
            $zkq = 0;
            $mjq = 0;
            $num = 0;
            $temp['user_id'] = $user_id;
            $temp['msg'] = '分享邀请获取礼包';
            $temp['integral'] = 0;
            $temp['status'] = 1;
            $temp['type'] = 2;
            $res2 = true;
            foreach ($arr_list['extend'] as $key => $vo) {
                for ($i = 1; $i <= $vo['number']; $i++) {
                    if ($vo['type_coupon'] == 1) {
                        $xcq++;
                    } else if ($vo['type_coupon'] == 2) {
                        $mjq++;
                    } else if ($vo['type_coupon'] == 3) {
                        $zkq++;
                    }
                    $num++;
                    $temp['coupon_id'] = $vo['coupon_id'];
                    $temp['pid'] = $vo['type_coupon'];
                    $temp['over_at'] = time() + $vo['validity_at'] * 60 * 60 * 24;
                    $temp['ticket_num'] = set_coupons_ticket_num($vo['type_coupon']);
                    $res2 = CouponGrantDetailRepository::add_one($temp);
                }
            }
            $str = '已发放洗车券：' . $xcq . '张，满减券：' . $mjq . '张，折扣券：' . $zkq . '张,共计发放' . $num . '张';
            $arrlog = [
                'user_id' => $user_id,
                'send_time' => date('Y-m-d H:i:s'),
                'msg' => $str,
                'type' => 3,
                'type_msg' => '用户邀请礼包'
            ];
            //将发放用户邀请礼包的记录记录日志
            $res3 = LogRepository::record_send_gift((array)$arrlog);

            #将人员设置为已发放
            ##获取当前满足人员的数量
            $arr_option2['where'] = ['user_id' => $user_id, 'type' => 0];
            $arr_option2['n_per_page'] = $arr_list['number'];
            $arr_option2['first'] = ['id'];
            $arr_option2['order'] = ['key' => 'id', 'value' => 'asc'];
            $arr_list = UserInviteRepository::get_all_to_limit((array)$arr_option2)->toarray();
            $last_id = '';

            foreach ($arr_list as $key => $vo) {
                $last_id = $vo['id'];
            }
            ##修改数据表状态
            $data2['type'] = 1;
            $where2 = ['user_id' => $user_id];
            $res4 = UserInviteRepository::edit_by_where((array)$where2, (array)$data2, (int)$last_id);
            if ($res2 && $res3 && $res4) {
                \DB::commit();
                return hello_success('邀请礼包发放成功');
            }
        } catch (\Exception $exception) {
            \DB::rollback();    //数据回滚
            return hello_error($exception->getMessage());
        }
    }

    //老用户回馈礼包
    public function send_gift_old()
    {
        \DB::beginTransaction();      //开启事物
        try {
            /**
             *  1：新年的第一天自动执行次函数
             *  2：验证当前礼包是否开启
             *  3：获取礼包的数据详情
             *  4：获取满足条件的所有用户信息
             *  5：将礼包发放给各个满足条件的用户
             *  6：记录礼包发放日志
             **/
            //验证邀请礼包是否开启（由于现在控制功能为完善，暂且不验证）

            $arr_option['field'] = ['id', 'age'];
            $arr_option['with'] = ['extend'];
            $arr_option['where'] = ['type' => 2];
            //获取平台设置的发放礼包配置信息
            $arr_list = GiftRepository::get_all((array)$arr_option)->toarray();
            $age2 = [];     //2年老用户礼包
            $age3 = [];     //3年老用户礼包
            $age5 = [];     //5年老用户礼包
            //#分别取出不同年限的礼包
            foreach ($arr_list as $key => $vo) {
                if ($vo['age'] == 2) {  //2年
                    $age2 = $vo['extend'];
                }
                if ($vo['age'] == 3) {  //3年
                    $age3 = $vo['extend'];
                }
                if ($vo['age'] == 5) {  //5年
                    $age5 = $vo['extend'];
                }
            }

            //获取用户的列表信息
            $time1 = date("Y-01-01 00:00:00", strtotime("-2 year")); //获取格式为2016-12-30 13:26:13
            $time2 = date("Y-01-01 00:00:00", strtotime("-3 year")); //获取格式为2016-12-30 13:26:13
            $time3 = date("Y-01-01 00:00:00", strtotime("-5 year")); //获取格式为2016-12-30 13:26:13
            $res2 = true;
            $res3 = true;
            $res5 = true;
            $xcq = 0;       //发放洗车券张数
            $zkq = 0;       //发放折扣券张数
            $mjq = 0;       //发放满减券张数
            $num = 0;       //发放所有种类优惠券的张数
            $ids = '';

            if (count($age2) > 0) {  //设置了2年礼包
                //# 获取满足2年并且小于3年的老用户
                $arr_list2 = UsersRepository::get_where_list((array)['time1' => $time1, 'time2' => $time2])->toarray();
                if (count($arr_list2) > 0) {
                    foreach ($arr_list2 as $key => $value) {
                        $ids .= $value['id'] . ',';
                        $temp2['user_id'] = $value['id'];
                        $temp2['msg'] = '2年老用户回馈礼包';
                        $temp2['integral'] = $value['integral_all'];  //当前用户的的总积分
                        $temp2['status'] = 1;
                        $temp2['type'] = 5;
                        foreach ($age2 as $k => $vo) {
                            for ($i = 1; $i <= $vo['number']; $i++) {
                                if ($vo['type_coupon'] == 1) {
                                    $xcq++;
                                } else if ($vo['type_coupon'] == 2) {
                                    $mjq++;
                                } else if ($vo['type_coupon'] == 3) {
                                    $zkq++;
                                }
                                $num++;
                                $temp2['coupon_id'] = $vo['coupon_id'];     //优惠券id
                                $temp2['pid'] = $vo['type_coupon'];         //优惠券类型
                                $temp2['over_at'] = time() + $vo['validity_at'] * 60 * 60 * 24;   //优惠券过期的时间
                                $temp2['ticket_num'] = set_coupons_ticket_num($vo['type_coupon']);      //随机生成优惠券的券号
                                $res2 = CouponGrantDetailRepository::add_one($temp2);
                            }
                        }
                    }
                    $str2 = '已发放洗车券：' . $xcq . '张，满减券：' . $mjq . '张，折扣券：' . $zkq . '张,共计发放' . $num . '张';
                    $arrlog = [
                        'user_id' => trim($ids, ','),
                        'send_time' => date('Y-m-d H:i:s'),
                        'msg' => $str2,
                        'type' => 2,
                        'type_msg' => '2年老用户回馈礼包'
                    ];
                    //将发放新用户注册礼包的记录记录日志
                    LogRepository::record_send_gift((array)$arrlog);
                }
            }
            $xcq = 0;       //重置洗车券发放的张数
            $zkq = 0;       //折扣券
            $mjq = 0;       //满减券
            $num = 0;
            $ids = '';
            if (count($age3) > 0) {  //设置了3年礼包
                //#获取满足3年并且小于5年的老用户
                $arr_list3 = UsersRepository::get_where_list((array)['time1' => $time2, 'time2' => $time3])->toarray();
                if (count($arr_list3) > 0) {
                    foreach ($arr_list3 as $key => $value) {
                        $ids .= $value['id'] . ',';
                        $temp3['user_id'] = $value['id'];
                        $temp3['msg'] = '3年老用户回馈礼包';
                        $temp3['integral'] = $value['integral_all'];
                        $temp3['status'] = 1;
                        $temp3['type'] = 5;
                        foreach ($age3 as $k => $vo) {
                            for ($i = 1; $i <= $vo['number']; $i++) {
                                if ($vo['type_coupon'] == 1) {
                                    $xcq++;
                                } else if ($vo['type_coupon'] == 2) {
                                    $mjq++;
                                } else if ($vo['type_coupon'] == 3) {
                                    $zkq++;
                                }
                                $num++;
                                $temp3['coupon_id'] = $vo['coupon_id'];
                                $temp3['pid'] = $vo['type_coupon'];
                                $temp3['over_at'] = time() + $vo['validity_at'] * 60 * 60 * 24;
                                $temp3['ticket_num'] = set_coupons_ticket_num($vo['type_coupon']);
                                $res3 = CouponGrantDetailRepository::add_one($temp3);
                            }
                        }
                    }
                    $str3 = '已发放洗车券：' . $xcq . '张，满减券：' . $mjq . '张，折扣券：' . $zkq . '张,共计发放' . $num . '张';
                    $arrlog = [
                        'user_id' => trim($ids, ','),
                        'send_time' => date('Y-m-d H:i:s'),
                        'msg' => $str3,
                        'type' => 2,
                        'type_msg' => '3年老用户回馈礼包'
                    ];
                    //将发放新用户注册礼包的记录记录日志
                    LogRepository::record_send_gift((array)$arrlog);
                }
            }

            $xcq = 0;       //重置洗车券的数量
            $zkq = 0;
            $mjq = 0;
            $num = 0;
            $ids = '';
            if (count($age5) > 0) {  //设置了5年礼包
                //#获取满足5年的老用户
                $arr_list5 = UsersRepository::get_where_list((array)['time1' => $time3])->toarray();
                if (count($arr_list5) > 0) {
                    foreach ($arr_list5 as $key => $value) {
                        $ids .= $value['id'] . ',';
                        $temp5['user_id'] = $value['id'];
                        $temp5['msg'] = '5年老用户回馈礼包';
                        $temp5['integral'] = $value['integral_all'];
                        $temp5['status'] = 1;
                        $temp5['type'] = 5;
                        foreach ($age5 as $k => $vo) {
                            for ($i = 1; $i <= $vo['number']; $i++) {
                                if ($vo['type_coupon'] == 1) {
                                    $xcq++;
                                } else if ($vo['type_coupon'] == 2) {
                                    $mjq++;
                                } else if ($vo['type_coupon'] == 3) {
                                    $zkq++;
                                }
                                $num++;
                                $temp5['coupon_id'] = $vo['coupon_id'];
                                $temp5['pid'] = $vo['type_coupon'];
                                $temp5['over_at'] = time() + $vo['validity_at'] * 60 * 60 * 24;
                                $temp5['ticket_num'] = set_coupons_ticket_num($vo['type_coupon']);
                                $res5 = CouponGrantDetailRepository::add_one($temp5);
                            }
                        }
                    }
                    $str5 = '已发放洗车券：' . $xcq . '张，满减券：' . $mjq . '张，折扣券：' . $zkq . '张,共计发放' . $num . '张';
                    $arrlog = [
                        'user_id' => trim($ids, ','),
                        'send_time' => date('Y-m-d H:i:s'),
                        'msg' => $str5,
                        'type' => 2,
                        'type_msg' => '5年老用户回馈礼包'
                    ];
                    //将发放新用户注册礼包的记录记录日志
                    LogRepository::record_send_gift((array)$arrlog);
                }
            }
            if ($res2 && $res3 && $res5) {
                \DB::commit();
                return hello_success('老用户回馈礼包发放成功');
            }
            return hello_error('没有设置礼包信息');
        } catch (\Exception $exception) {
            \DB::rollback();    //数据回滚
            return hello_error($exception->getMessage());
        }
    }


    /**
     *    会员升级发放会员等级礼包
     *    hinq 2019 09 26
     *    先将用户获得的积分更新到数据库中在调用此接口
     **/
    public function send_upgrade_material_benefits(int $user_id)
    {
        try {
            if (empty($user_id)) {
                return ['state' => 1, 'msg' => '用户id不能为空', 'data' => [], 'error' => ''];
            }
            //获取用户的积分信息
            $user_info = UsersRepository::get_one((int)$user_id, (array)['field' => ['id', 'integral', 'integral_all']]);
            if( empty( $user_info->first() ) ){
                return hello_error('参数错误');
            }
            $user_info = $user_info->toarray();
            //获取会员等级列表
            $user_level = UsersLevelRepository::get_all((array)['order' => ['key' => 'min_integral', 'value' => 'asc'], 'field' => ['id', 'name', 'min_integral', 'max_integral', 'equities']])->toArray();

            $user_new_level = [];  //会员所属的会员等级
            //检测当前用户会员等级
            foreach ( $user_level as $key => $value ) {
                //      会员当前的总积分         >=      会员等级的最低积分      会员当前的总积分          <=     会员等级的最大积分
                if ($user_info['integral_all'] >= $value['min_integral'] && $user_info['integral_all'] <= $value['max_integral']) {
                    $user_new_level = $value;  //获取当前会员所属的会员等级
                }
            }
            //获取当前所属等级的所有权益
            $equities_ids = explode(',', $user_new_level['equities']);  //当前等级的所有权益
            $level_equities = EquitiesRepository::get_all_by_whereIn((array)$equities_ids, (array)['with' => ['get_equities','get_equities.get_coupon']])->toArray();

            $coupon_list = [];  //权益的优惠券礼包集合
            foreach ($level_equities as $key => $value) {
                if (count($value['get_equities']) > 0 ) {
                    //获取需要发放的优惠券数据
                    foreach ($value['get_equities'] as $k => $val) {
                        if( !empty( $val['get_coupon'] ) ){  //后台设置的优惠可能被删除 导致找不到优惠券的信息  后面发放的时候会保存
                            //升级时一次性优惠券 和每月固定的优惠券 在会员升级时都发放一次
                            $coupon_list['coupon'][] = $val['coupon_id'];    //发放的优惠券id
                            $coupon_list['num'][] = $val['num'];            //发放的数量
                            $coupon_list['equities'][] = $value['id'];          //权益id集合
                        }
                    }
                }
            }

            if (count($coupon_list) <= 0) {
                return ['state' => 0, 'msg' => '暂无礼包发放', 'data' => [], 'error' => ''];
            }

            //获取权益礼包中包含的所有优惠券信息
            $coupon = CouponsRepository::get_all_by_whereIn((array)array_unique($coupon_list['coupon']), (array)['field' => ['id', 'pid', 'validity_at']])->toarray();
            if( count( $coupon) <= 0  ){
                return hello_error('设置优惠券信息有误，请检查设置信息');
            }
            $coupon_pids = []; //
            foreach ($coupon as $key => $value) {
                $coupon_pids[$value['id']]['pid'] = $value['pid'];
                $coupon_pids[$value['id']]['validity_at'] = $value['validity_at'];
            }

            //检测当前用户是否已经发放过升级礼包
            foreach ($coupon_list['coupon'] as $key => $value) {
                $arr_map['user_id'] = $user_id;
                $arr_map['coupon_id'] = $value;
                $arr_map['type'] = 1;
                $arr_map['user_level'] = $user_new_level['id'];
                $arr_map['equities'] = $coupon_list['equities'][$key];
                //升级礼包是一起发放的 如果有发放过升级礼包所有的礼包都不发放 否则发放
                if (CouponGrantDetailRepository::get_count_by_where((array)$arr_map) >= 1) {
                    return ['state' => 0, 'msg' => '升级礼包已发放，请勿重复发放', 'data' => [], 'error' => ''];
                }
                $temp['user_id'] = $user_id;
                $temp['coupon_id'] = $value;
                $temp['msg'] = '会员升级发放会员等级礼包';
                $temp['integral'] = $user_info['integral_all'];
                $temp['status'] = 1;
                $temp['type'] = 1;
                $temp['user_level'] = $user_new_level['id'];   //用户当前级别id
                $temp['equities'] = $coupon_list['equities'][$key];     //
                for ($i = 1; $i <= $coupon_list['num'][$key]; $i++) {   //根据优惠券设置方法的张数进行循环发放  后台可以设置发放多张同样的优惠券
                    $temp['pid'] = $coupon_pids[$value]['pid'];
                    $temp['over_at'] = $coupon_pids[$value]['validity_at'] * 3600 * 24 + time();  //优惠券过期时间
                    $temp['ticket_num'] = set_coupons_ticket_num($coupon_pids[$value]['pid']);  //随机生成优惠券发放的券号（唯一）
                    $res = CouponGrantDetailRepository::add_one($temp);
                    $result = hi_check_res($res, 'edit_one');
                    if ($result['state'] != 0) {
                        return ['state' => 1, 'msg' => '升级礼包发放失败', 'data' => [], 'error' => ''];
                    }
                }
            }
            $str = '已发放用户升级礼包(' . $user_new_level['name'] . ')';
            $arrlog = [
                'user_id' => $user_id,
                'send_time' => date('Y-m-d H:i:s'),
                'msg' => $str,
                'type' => 6,
                'type_msg' => '用户升级等级礼包'
            ];
            //将发放新用户注册礼包的记录记录日志
            LogRepository::record_send_gift((array)$arrlog);
            return ['state' => 0, 'msg' => 'ok', 'data' => [], 'error' => ''];
        } catch (\Exception $exception) {
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }

    }


    /**
     *  修改用户的积分（添加、减少） 【给用户添加、扣除积分的唯一入口】
     *  积分兑换比  1:1  不足1积分的舍弃    给用户添加积分后 调用是否需要给用户发放会员等级升级礼包
     *  hinq 2019 09 24
     *  $arrInput['user_id']   int    用户id
     *  $arrInput['total_fee']   int   金额
     *  $arrInput['type']    int   1：增加积分   2：减扣积分
     *  $arrInput['order_id']     int  关联的订单id
     *  $arrInput['order_type']    int   订单类型   1：积分兑换   2：检测站预约年检  3：普通订单 4：服务订单  5:道路救
     *  $arrInput['remarks']    string  备注   流水说明
     *  以上参数都是必填项
     *  接口位置 UserService::user_integral_change()
     **/
    public function user_integral_change(array $arrInput, array $user_info = [])
    {
        try {
            if (empty($arrInput['total_fee']) && $arrInput['total_fee'] != 0) {
                return ['state' => 1, 'msg' => '积分不能为空', 'data' => [], 'error' => ''];
            }

            if (empty($arrInput['type'])) {
                return ['state' => 1, 'msg' => '请设置积分操作类型', 'data' => [], 'error' => ''];
            }

            if (empty($arrInput['order_id'])) {
                return ['state' => 1, 'msg' => '请设置关联订单', 'data' => [], 'error' => ''];
            }

            if (empty($arrInput['order_type'])) {
                return ['state' => 1, 'msg' => '请设置关联订单类型', 'data' => [], 'error' => ''];
            }

            if (empty($arrInput['remarks'])) {
                return ['state' => 1, 'msg' => '请设置备注信息', 'data' => [], 'error' => ''];
            }

            $arrInput['integral'] = (int)$arrInput['total_fee'] * 100;
            $uid = $arrInput['user_id'];
            $arr_where = $arrInput;
            unset($arr_where['remarks']);
            unset($arr_where['integral']);
            unset($arr_where['total_fee']);
//            $count = UsersIntegralRepository::get_count_by_where( (array) $arr_where );

//            unset( $arr_where);
//            if( $count >= 1 ){
//                return ['state'=> 1,'msg'=>'该订单已评论','data'=>[],'error'=>''];
//            }

            if (empty($user_info)) {
                //获取用户的积分信息
                $user_info = UsersRepository::get_one((int)$uid, (array)['field' => ['id', 'integral', 'integral_all', 'status']]);
                if (empty($user_info->first())) {
                    return ['state' => 1, 'msg' => '获取用户信息失败', 'data' => [], 'error' => ''];
                }
                $user_info = $user_info->toArray();
            }
            if ($user_info['status'] != 1) {
                return ['state' => 1, 'msg' => '用户禁用，不可操作', 'data' => [], 'error' => ''];
            }

            //添加用户积分流水
            $data['user_id'] = $uid;
            $data['type'] = $arrInput['type'];      //积分操作类型  1：增加积分  2：扣除积分
            $data['deduct'] = (int)$arrInput['integral'] / 100;  //向下取整  1.23  1.95 都取1 小数部分都舍弃
            if ($arrInput['type'] == 1) {
                //  操作后的积分   =   用户当前的积分    +  需要操作的积分
                $data['surplus'] = $user_info['integral'] + (int)$arrInput['integral'] / 100;
            } else {
                //用户积分小于当前需要操作 的积分
                if ($user_info['integral'] < (int)$arrInput['integral'] / 100) {
                    return ['state' => 1, 'msg' => '当前积分操作有误，请核实', 'data' => [], 'error' => ''];
                }
                //  操作后的积分   =   用户当前的积分    -   需要操作的积分
                $data['surplus'] = $user_info['integral'] - (int)$arrInput['integral'] / 100;
            }
            $data['order_id'] = (int)$arrInput['order_id'];     //关联的订单id
            $data['order_type'] = $arrInput['order_type'];      //1：积分兑换   2：检测站预约年检  3：维修店订单  4:道路救援   5:订单评论
            $data['remarks'] = $arrInput['remarks'];            //备注信息

            $res = UsersIntegralRepository::add_one($data);
            if ($arrInput['type'] == 1) {   //给用户添加积分
                $temp['integral'] = $user_info['integral'] + (int)$arrInput['integral'] / 100;
                $temp['integral_all'] = $user_info['integral_all'] + (int)$arrInput['integral'] / 100;
                $temp['id'] = $uid;
                $res2 = UsersRepository::edit_one((array)$temp);
            } else {     //给用户扣除积分
                $res2 = UsersRepository::decrease_num((int)$uid, 'integral', (int)$arrInput['integral'] / 100);
            }

            $result = hi_check_res($res2, 'edit_one');

            if ($result['state'] != 0) {
                return ['state' => 1, 'msg' => '操作失败', 'data' => [], 'error' => ''];
            }
            if ($arrInput['type'] == 1) {  //添加积分
                //判断添加完积分后用户是否升级会员等级，并且发放会员等级礼包
                self::send_upgrade_material_benefits((int)$uid);
            }
            return hello_success('ok');
        } catch (\Exception $exception) {
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }
    }


    /**
     *    计算商品使用优惠券后的价格
     *    hinq 2019 09 10
     *    $arrInput['goods_id']       商品的id
     *    $arrInput['coupon_id']      优惠券的id
     *    $arrInput['type']           商品的类型 1：维修站商品（car_repairstore_goods）
     *  return double  ****.**
     *  GoodsService::goods_coupon_imputed_price();
     **/
    public function goods_coupon_imputed_price(array $arrInput)
    {
        try {
            //获取商品实际需要支付的价格的信息
            $arr_where['field'] = ['id', 'price'];
            $arr_goods_info = RepairstoreGoodsRepository::get_one((int)$arrInput['goods_id'], (array)$arr_where);
            if (empty($arr_goods_info->first())) {
                return ['state' => 1, 'msg' => '获取商品信息失败', 'data' => [], 'error' => ''];
            }

            //获取优惠券的信息
            $arr_where['field'] = ['id', 'pid', 'price', 'discount_num', 'price_all'];
            $arr_coupon_info = CouponsRepository::get_one((int)$arrInput['coupon_id'], (array)$arr_where);
            if (empty($arr_coupon_info->first())) {
                return ['state' => 0, 'msg' => '', 'data' => ['goods_price' => $arr_goods_info['price'], 'price' => $arr_goods_info['price'], 'coupon_price' => '0.00'], 'error' => ''];
            }

            // $coupon_types = ['1'=>'洗车券','2'=>'满减券','3'=>'折扣券'];
            $price = 0;
            // 商品的价格   <    优惠券的价格      不可以使用优惠券
            if ($arr_goods_info['price'] < $arr_coupon_info['price']) {   //当前订单的价格不支持使用指定的优惠券  不能返回错
                return ['state' => 0, 'msg' => '', 'data' => ['goods_price' => $arr_goods_info['price'], 'price' => $arr_goods_info['price'], 'coupon_price' => '0.00'], 'error' => ''];
            }

            $coupon_price = '0.00';
            //通过优惠券的类型计算优惠后的价格
            if ($arr_coupon_info['pid'] == 2) {  //满减券
                $price = sprintf("%.2f", $arr_goods_info['price'] - $arr_coupon_info['price']);  //实际支付金额 = 订单实际支付金额 - 优惠券优惠券的金额
                $coupon_price = $arr_coupon_info['price'];   //优惠金额
            } else if ($arr_coupon_info['pid'] == 3) {   //折扣券
                $price = sprintf("%.2f", $arr_goods_info['price'] * $arr_coupon_info['discount_num'] / 10);//实际支付金额 = 订单实际支付金额 * 优惠券优惠券的折扣数量 / 10
                $coupon_price = sprintf("%.2f", $arr_goods_info['price'] - sprintf("%.2f", $arr_goods_info['price'] * $arr_coupon_info['discount_num'] / 10));  //优惠金额  = 订单实际金额 - 优惠券折价后的金额
            } else if ($arr_coupon_info['pid'] == 1) {
                return ['state' => 1, 'msg' => '该优惠券暂不支持使用', 'data' => [], 'error' => ''];
            }
            //  goods_price： 订单的实际金额   price ： 实际支付的金额     coupon_price： 优惠金额
            return ['state' => 0, 'msg' => '', 'data' => ['goods_price' => $arr_goods_info['price'], 'price' => $price, 'coupon_price' => $coupon_price], 'error' => ''];
        } catch (\Exception $exception) {
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }
    }


    /**
     *  计算订单的优惠价格 其实我们留下的什么都没有
     *  hinq 2019 11 16
     *  $arr_input['order_amount']  订单的总价格
     *  $arr_input['type']          类型   1： 优惠券  2：活动
     *  $arr_input['coupon_id']     优惠券id  5
     *  $arr_input['activity_id']   活动id
     *
     **/
    public function order_imputed_price(array $arr_input)
    {
        try {
            $data['coupon_price'] = 0;     // 优惠券的券面价格
            $data['order_amount'] = $arr_input['order_amount'];    //订单总价格
            $data['price'] = $arr_input['order_amount'];    //优惠后的价格【最总支付的价格】

            switch ($arr_input['type']) {
                case 1:
                    //获取优惠券的信息
                    $arr_where['field'] = ['id', 'pid', 'price', 'discount_num', 'price_all'];
                    $arr_coupon = CouponsRepository::get_one((int)$arr_input['coupon_id'], (array)$arr_where);
                    if (empty($arr_coupon->first())) {
                        return hello_error('优惠券id错误');
                    }
                    $temp = $arr_coupon->toArray();
                    //       订单的总金额            <      优惠券的最低消费金额
                    if ($arr_input['order_amount'] < $temp['price_all']) {
                        return hello_success('ok', $data);
                    }
                    if ($temp['pid'] == 2) {  // 满减
                        //     最终优惠价格                订单总金额               优惠券金额
                        $data['coupon_price'] = (string)round($temp['price'], 2);
                        $data['order_amount'] = $arr_input['order_amount'];
                        $data['price'] = (string)round($arr_input['order_amount'] - $temp['price'], 2);
                        //这里计算必须确保  $data['coupon_price'] +  $data['price'] === $data['order_amount']  不允许有一丁点的误差
                    } else if ($temp['pid'] == 3) {  //折扣
                        $coupon_price = (string)round($arr_input['order_amount'] - $arr_input['order_amount'] * $temp['discount_num'] / 100, 2);
                        //     最终优惠价格                订单总金额               优惠券金额
                        $data['coupon_price'] = $coupon_price;
                        $data['order_amount'] = $arr_input['order_amount'];
                        $data['price'] = (string)round($arr_input['order_amount'] - $coupon_price, 2);

                        //这里计算必须确保  $data['coupon_price'] +  $data['price'] === $data['order_amount']  小数位不允许有一丁点的误差
                    }
                    break;
                case 2:
                    //获取活动的信息
                    $arr_option['where'] = ['status' => 1];
                    $arr_option['with'] = ['activity_extend'];
                    $arr_option['field'] = ['id', 'type', 'status', 'over_time', 'start_time'];
                    $arr_activity = ActivityRepository::get_one((int)$arr_input['activity_id'], (array)$arr_option);
                    if (empty($arr_activity->first())) {
                        return hello_error('活动信息错误');
                    }
                    $temp = $arr_activity->toArray();
                    $arr = [];
                    //判断当前订单金额最优满足的优惠力度
                    foreach ($temp['activity_extend'] as $key => $item) {
                        //    订单总金额                        最低消费金额
                        if ($arr_input['order_amount'] >= $item['price_all']) {
                            $arr = $item;
                        }
                    }

                    if (count($arr) == 0) {
                        return hello_success('ok', $data);
                    }
                    //当前活动不在进行中 直接返回原始数据
                    if (!($temp['start_time'] <= time() && $temp['over_time'] >= time())) {
                        return hello_success('ok', $data);
                    }

                    switch ($temp['type']['type']) {
                        case 1:
                            //     最终优惠价格                订单总金额               优惠券金额
                            $data['coupon_price'] = (string)round($arr['price'], 2);
                            $data['order_amount'] = $arr_input['order_amount'];
                            $data['price'] = (string)round($arr_input['order_amount'] - $arr['price'], 2);
                            //这里计算必须确保  $data['coupon_price'] +  $data['price'] === $data['order_amount']  不允许有一丁点的误差
                            break;
                        case 2:
                            $coupon_price = (string)round($arr_input['order_amount'] * $arr['price'] / 10, 2);
                            $data['coupon_price'] = (string)round($arr_input['order_amount'] - $coupon_price, 2);
                            $data['order_amount'] = $arr_input['order_amount'];
                            $data['price'] = $coupon_price;
                            //这里计算必须确保  $data['coupon_price'] +  $data['price'] === $data['order_amount']  小数位不允许有一丁点的误差
                            break;
                    }
            }
            return hello_success('ok', $data);
        } catch (\Exception $exception) {
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }
    }

    /**
     *  订单结算优惠券补贴价格
     *  hinq 2020 3 12
     *  $arr_input['order_price']   订单的总金额
     *  $arr_input['coupon_id']   优惠券id
     *  根据优惠券的类型计算出当前订单优惠的价格（ 满减券： 优惠券设计的优惠价格   折扣券： 订单的总金额 * 优惠券设计的折扣比例 / 100 ）
     *  在计算补贴价格（ 已经计算好的优惠价格 * 优惠券设计的补贴比例 / 100 ）
     *  如果订单的总金额或优惠券信息获取失败， 将直接返回订单总价，其他价格将不会进行计算
     *
     **/
    public function order_settlement_amount(array $arr_input)
    {
        try {
            $data['order_price'] = $arr_input['order_price'];    //订单的价格
            $data['assistance_payment'] = 0;    //补助的价格
            $data['coupon_price'] = 0;    //优惠的价格
            $data['subsidy'] = 0;    //补助比例

            //获取指定优惠券的详细信息
            $arr_option['field'] = ['id', 'pid', 'discount_num', 'price_all', 'price', 'subsidy'];
            $coupon_info = CouponsRepository::get_one((int)$arr_input['coupon_id'], (array)$arr_option);
            if (empty($coupon_info->first())) {
                return hello_success('优惠券id错误', $data);
            }
            $coupon_info = $coupon_info->toarray();
            //  优惠券最低消费金额   <    订单的总金额
            if ($coupon_info['price_all'] < $data['order_price']) {
                return hello_success('当前订单价格不支持使用次优惠券', $data);
            }
            //当前订单优惠的价格
            switch ($coupon_info['pid']) {
                case 2:   //满减券
                    $coupon_price = (string)round($coupon_info['price'], 2);  //优惠的价格
                    if (empty($coupon_info['subsidy'])) {        //补助比例为空
                        $assistance_payment = 0;   //补助的价格
                        $subsidy = 0;
                    } else {
                        $assistance_payment = (string)round($coupon_price * $coupon_info['subsidy'] / 100, 2);   //补助的价格
                        $subsidy = $coupon_info['subsidy'] . '%';
                    }
                    break;
                case 3:     //折扣券
                    $coupon_price = (string)round($coupon_info['discount_num'] * $data['order_price'] / 100, 2);  //优惠的价格
                    if (empty($coupon_info['subsidy'])) {         //补助比例为空
                        $assistance_payment = 0;   //补助的价格
                        $subsidy = 0;
                    } else {
                        $assistance_payment = (string)round($coupon_price * $coupon_info['subsidy'] / 100, 2);   //补助的价格
                        $subsidy = $coupon_info['subsidy'] . '%';
                    }
                    break;
                default:
                    return hello_success('ok', $data);
                    break;
            }
            $data['order_price'] = $arr_input['order_price'];    //订单的价格
            $data['assistance_payment'] = $assistance_payment;    //补助的价格
            $data['coupon_price'] = $coupon_price;    //优惠的价格
            $data['subsidy'] = $subsidy;    //补助比例

            return hello_success('ok', $data);
        } catch (\Exception $exception) {
            return hello_error($exception->getMessage());
        }
    }


    /**
     *  订单结算优惠券补贴价格  跟上面的函数相似
     *  hinq 2020 3 12
     *  $arr_input['order_price']   订单的总金额
     *  $arr_input['coupon_price']   订单已经计算好的优惠金额
     *  $arr_input['coupon_id']   优惠券id
     **/
    public function order_settlement_amount3(array $arr_input)
    {
        try {
            //获取优惠券的信息
            $arr_option['field'] = ['id', 'subsidy', 'pid', 'price', 'discount_num', 'price_all'];
            $coupon_info = CouponsRepository::get_one((int)$arr_input['coupon_id'], (array)$arr_option);
            $data = [
                'order_price' => $arr_input['order_price'],
                'coupon_price' => $arr_input['coupon_price'],
                'assistance_payment' => 0,
                'subsidy' => 0
            ];
            switch ($coupon_info['pid']) {
                case 2:   //满减券
                    $data['coupon_price'] = $coupon_info['price'];//优惠价格
                    $data['assistance_payment'] = $coupon_info['price'] * $coupon_info['subsidy'] / 100;
                    $data['subsidy'] = $coupon_info['subsidy'] . '%';
                    break;
                case 3:   //折扣券
                    $data['coupon_price'] = $arr_input['order_price'] * $coupon_info['discount_num'] / 100;//优惠价格
                    $data['coupon_price'] = (string)round("785.456", 2);//优惠价格
                    $data['assistance_payment'] = (string)round($data['coupon_price'] * $coupon_info['subsidy'] / 100, 2); //优惠补贴价格
                    $data['subsidy'] = $coupon_info['subsidy'] . '%';   //优惠补贴比例
                    break;
                default:
                    return hello_success('ok', $data);
                    break;
            }
            return hello_success('ok', $data);
        } catch (\Exception $exception) {
            return hello_success($exception->getMessage());
        }
    }




    /**
     *  获取已设置的敏感词库内容
     *  hinq 2020 6 11
     *
     **/
    public function get_all(){
        $where = ['status'=>1,'type'=>1];
        $arr_list = SensitivityRepository::get_one_where( (array) $where );
        if( empty( $arr_list->first())){
            return hello_success('ok',[]);
        }
        return hello_success('ok',$arr_list);
    }

    /**
     *  保存、更新敏感词库
     *  hinq 2020 6 11
     *
     **/
    public function sensitivity_update( array $arr_input ){
        try{
            if( empty( $arr_input['content'] ) ){
                return hello_error('敏感词库内容不能为空');
            }
            $info = SensitivityRepository::get_one_where( (array) ['type'=>1 , 'status'=>1]);
            if( empty( $info->first() ) ){   //添加数据
                $data['type'] = 1;
                $data['status'] = 1;
                //用户有可能输入全角下的“＊”
                $arr_input['content'] = str_replace('＊','*' , $arr_input['content']);
                $new_content = explode( '*', trim( $arr_input['content']) );
                $new_content = array_unique( $new_content );
                $content = implode( '*' , $new_content );
                $data['content'] = $content;
                $res = SensitivityRepository::add_one( (array) $data );
                if( empty( $res ) ){
                    return hello_error('设置失败，请稍后重试');
                }
//                \Redis::set( 'sensitivity' , $content );
                return hello_success('ok');
            }else{
                //用户有可能输入全角下的“＊”
                $arr_input['content'] = str_replace('＊','*' , $arr_input['content']);
                $new_content = explode( '*', $arr_input['content'] );
                $new_content = array_unique( $new_content );
                $content = implode( '*' , $new_content );
                $temp['content'] = $content;
                $res = SensitivityRepository::edit_one_where( (array) ['type'=>1 , 'status'=>1] , (array) $temp );
                if( empty( $res ) ){
                    return hello_error('设置失败，请稍后重试');
                }
//                \Redis::set( 'sensitivity' , $content );
                return hello_success('设置成功');
            }
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage() );
        }
    }


    /**
     *  检索敏感词是否已经添加
     *  hinq 2020 6 12
     *
     **/
    public function sensitivity_search( string $title ){
        try{
            if( empty( $title ) ){
                return hello_error('敏感词不能为空');
            }
            $where = ['status'=>1,'type'=>1];
            $arr_list = SensitivityRepository::get_one_where( (array) $where );
            if( empty( $arr_list->first() ) ){
                return hello_error('请先添加敏感词库');
            }
            $content = $arr_list->toarray()['content'];
            $content_list = explode( '*' , $content);
            if( in_array( $title , $content_list ) ){
                return hello_error('该敏感词已存在词库中');
            }else{
                return hello_success('ok');
            }
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage());
        }
    }
}